//
//  DiscoverViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/6/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "DiscoverViewController.h"
#import "DiscoverTableViewCell.h"

@interface DiscoverViewController ()<SDCycleScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIView * lineView;
@property (nonatomic, strong)UIButton * informationBtn;
@property (nonatomic, strong)UIButton * storyBtn;
@property (nonatomic, strong)UIButton * dynamicBtn;
@property (nonatomic, strong)NSMutableArray * cellData;
@property (nonatomic, assign)int currentPage;
@property (nonatomic, strong)NSString * disnumID;//底部新闻ID
@property (nonatomic, assign)int stateNum;//下栏状态
@end

@implementation DiscoverViewController(networking)
- (void)bottomClassifyNews{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr,
                           @"disnum":self.disnumID,
                           @"size":@"5",
                           @"page":@(self.currentPage)
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"disnum":self.disnumID,
                               @"size":@"5",
                               @"page":@(self.currentPage),
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/discover/index?api=api1004"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        NSLog(@"成功");
                        if (self.currentPage == 1) {
                            [self.cellData removeAllObjects];
                        }
                        [self.cellData addObjectsFromArray:jsonData[@"body"]];
                        [self.tableView reloadData];
    //                if (self.stateNum == 0) {
    //                    [UIView animateWithDuration:0.5 animations:^{
    //                        self.lineView.frame = CGRectMake(0, 41/WIDTH_6_SCALE, 44/WIDTH_6_SCALE, 2/WIDTH_6_SCALE);
    //                        self.lineView.centerX = self.informationBtn.centerX;
    //                    }];
    //                }else if (self.stateNum == 1){
    //                    [UIView animateWithDuration:0.5 animations:^{
    //                        self.lineView.frame = CGRectMake(0, 41/WIDTH_6_SCALE, 44/WIDTH_6_SCALE, 2/WIDTH_6_SCALE);
    //                        self.lineView.centerX = self.storyBtn.centerX;
    //                    }];
    //                }else if (self.stateNum == 2){
    //                    [UIView animateWithDuration:0.5 animations:^{
    //                        self.lineView.frame = CGRectMake(0, 41/WIDTH_6_SCALE, 44/WIDTH_6_SCALE, 2/WIDTH_6_SCALE);
    //                        self.lineView.centerX = self.dynamicBtn.centerX;
    //                    }];
    //                }
                    }else{
                        NSLog(@"失败");
                        ShowMessage(jsonData[@"msg"]);
                    }
                }else{
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end

@implementation DiscoverViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    
    self.disnumID = @"0";
    self.currentPage = 1;
//    [self bottomClassifyNews];//网络接口
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
}
#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - TABBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[DiscoverTableViewCell class] forCellReuseIdentifier:NSStringFromClass([DiscoverTableViewCell class])];
        __weak typeof (self)weakSelf = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.currentPage = 1;
            [self bottomClassifyNews];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.currentPage ++;
            [self bottomClassifyNews];
        }];
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100/WIDTH_6_SCALE)];
        //轮播图
        self.cycleScrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 0, SCREEN_WIDTH - 36/WIDTH_6_SCALE, 182/WIDTH_6_SCALE)];
        self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"3"];
        self.cycleScrollView.delegate = self;
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        self.cycleScrollView.currentPageDotColor = [UIColor whiteColor];
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        [_headerView addSubview:self.cycleScrollView];
        //分割线
        UIView * upTopLineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.cycleScrollView.bottom + 16/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        upTopLineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:upTopLineView];
        //灰色背景
        UIView * upBorderView = [[UIView alloc] initWithFrame:CGRectMake(0, upTopLineView.bottom, SCREEN_WIDTH, 13/WIDTH_6_SCALE)];
        upBorderView.backgroundColor = getColor(grayBGColor);
        [_headerView addSubview:upBorderView];
        //分割线
        UIView * upBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, upBorderView.bottom, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        upBottomLineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:upBottomLineView];
        //网贷课堂
        UIButton * netCreditBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, upBottomLineView.bottom + 16/WIDTH_6_SCALE, (SCREEN_WIDTH - 36/WIDTH_6_SCALE - 11/WIDTH_6_SCALE)/2, 84/WIDTH_6_SCALE)];
//        [netCreditBtn setTitle:@"网贷课堂" forState:UIControlStateNormal];
//        [netCreditBtn setBackgroundColor:[UIColor brownColor]];
        [netCreditBtn setImage:[UIImage imageNamed:@"wangdaiketang"] forState:UIControlStateNormal];
        [_headerView addSubview:netCreditBtn];
        //重大事件
        UIButton * eventBtn = [[UIButton alloc] initWithFrame:CGRectMake(netCreditBtn.right + 11/WIDTH_6_SCALE, netCreditBtn.top, netCreditBtn.width, netCreditBtn.height)];
//        [eventBtn setBackgroundColor:[UIColor greenColor]];
//        [eventBtn setTitle:@"重大事件" forState:UIControlStateNormal];
        [eventBtn setImage:[UIImage imageNamed:@"zhongdashijian"] forState:UIControlStateNormal];
        [_headerView addSubview:eventBtn];
        //分割线
        UIView * downTopLineView = [[UIView alloc] initWithFrame:CGRectMake(0, eventBtn.bottom + 16/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        downTopLineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:downTopLineView];
        //灰色背景
        UIView * downBorderView = [[UIView alloc] initWithFrame:CGRectMake(0, downTopLineView.bottom, SCREEN_WIDTH, 13/WIDTH_6_SCALE)];
        downBorderView.backgroundColor = getColor(grayBGColor);
        [_headerView addSubview:downBorderView];
        //分割线
        UIView * downBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, downBorderView.bottom, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        downBottomLineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:downBottomLineView];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, downBottomLineView.bottom);
    }return _headerView;
}
- (NSMutableArray *)cellData{
    if (!_cellData) {
        _cellData = @[].mutableCopy;
    }return _cellData;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DiscoverTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DiscoverTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellData[indexPath.row];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellData.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44/WIDTH_6_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 115/WIDTH_6_SCALE;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44/WIDTH_6_SCALE)];
    sectionView.backgroundColor = [UIColor whiteColor];
    //按钮参数
    CGFloat btnW = 60/WIDTH_6_SCALE;
    CGFloat btnBorder = (SCREEN_WIDTH - 76/WIDTH_6_SCALE - 3*btnW)/2;//按钮间隔
    CGFloat btnH = 34/WIDTH_6_SCALE;
    //行业资讯
    self.informationBtn = [[UIButton alloc] initWithFrame:CGRectMake(38/WIDTH_6_SCALE, 5/WIDTH_6_SCALE, btnW, btnH)];
    [self.informationBtn setTitle:@"行业资讯" forState:UIControlStateNormal];
    [self.informationBtn addTarget:self action:@selector(sectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.informationBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.informationBtn setBackgroundColor:[UIColor clearColor]];
    self.informationBtn.titleLabel.font = DEF_FontSize_12;
    [sectionView addSubview:self.informationBtn];
    //中裕故事
    self.storyBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.informationBtn.right + btnBorder, self.informationBtn.top, self.informationBtn.width, self.informationBtn.height)];
    [self.storyBtn setTitle:@"中裕故事" forState:UIControlStateNormal];
    [self.storyBtn addTarget:self action:@selector(sectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.storyBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.storyBtn setBackgroundColor:[UIColor clearColor]];
    self.storyBtn.titleLabel.font = DEF_FontSize_12;
    [sectionView addSubview:self.storyBtn];
    //中裕动态
    self.dynamicBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.storyBtn.right + btnBorder, self.storyBtn.top, self.storyBtn.width, self.storyBtn.height)];
    [self.dynamicBtn setTitle:@"中裕动态" forState:UIControlStateNormal];
    [self.dynamicBtn addTarget:self action:@selector(sectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.dynamicBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.dynamicBtn setBackgroundColor:[UIColor clearColor]];
    self.dynamicBtn.titleLabel.font = DEF_FontSize_12;
    [sectionView addSubview:self.dynamicBtn];

    //按钮下面横线
    self.lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 44/WIDTH_6_SCALE - 3/WIDTH_6_SCALE, 44/WIDTH_6_SCALE, 2/WIDTH_6_SCALE)];
    self.lineView.centerX = self.informationBtn.centerX;
    self.lineView.backgroundColor = [UIColor orangeColor];
    [sectionView addSubview:self.lineView];
    
    //分割线
    UIView * bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.bottom - 1/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    bottomLineView.backgroundColor = getColor(grayColor);
    [sectionView addSubview:bottomLineView];
    if (self.stateNum == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.lineView.centerX = self.informationBtn.centerX;
        }];
    }else if (self.stateNum == 1){
        [UIView animateWithDuration:0.5 animations:^{
            self.lineView.centerX = self.storyBtn.centerX;
        }];
    }else if (self.stateNum == 2){
        [UIView animateWithDuration:0.5 animations:^{
            self.lineView.centerX = self.dynamicBtn.centerX;
        }];
    }

    return sectionView;
}
#pragma mark - action
- (void)sectionBtnClick:(UIButton *)sender{
    self.currentPage = 1;
    if (sender.left>SCREEN_WIDTH/2) {
        self.disnumID = @"2";
        self.stateNum = 2;
        [self bottomClassifyNews];
    }else if (sender.left<SCREEN_WIDTH/2 && sender.right>SCREEN_WIDTH/2) {
        self.disnumID = @"1";
        self.stateNum = 1;
        [self bottomClassifyNews];
    }else if (sender.right < SCREEN_WIDTH/2) {
        self.disnumID = @"0";
        self.stateNum = 0;
        [self bottomClassifyNews];
    }
    
}
@end
